package com.javabasic2.pjchatserver;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import com.javabasic2.packet.PJChatPacket;

public class NetUnit extends Thread {
	private boolean running = false;
	private ChatFrame frame;
	private int unitNumber;
	private String unitName;
	private int score;
	public Socket socket;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	public boolean isRunning() { return running; }
	
	public NetUnit(ChatFrame frame, Socket socket) throws IOException {
		setScore(0);
		this.frame = frame;
		this.socket = socket;
		oos= new ObjectOutputStream(socket.getOutputStream()); 
        ois= new ObjectInputStream(socket.getInputStream());   //Data readData= (Data)ois.readObject(); 
		setDaemon(true);
	}
	//데이터 수신 메서드 (쓰레드 - 비동기 수신)
	public void run() {
		running = true;	
		while (running) {
			try {
				if (socket.getInputStream().available() > 0) {
					Object packetTransfer;
					try {
						packetTransfer = ois.readObject();
						PJChatPacket temp = (PJChatPacket)packetTransfer;
					frame.processMessage(this, packetTransfer);//frame에 수신된 메시지 처리 요청
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				} else {
					try {
						Thread.sleep(10);
					} catch (Exception ex) {}
				}
			} catch (IOException ex) {
				ex.printStackTrace();
				doClose();
				running = false;
			}
		}
	}
	//데이터 전송 메서드
	public void doSend(Object transfer) {
		PJChatPacket temp = (PJChatPacket)transfer;
		try {
			oos.writeObject(transfer);
			oos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void doStop() {
		running = false;//쓰레드 중지
		doClose();	//네트워크 자원 해제 (연결 종료)
	}
	private void doClose() {
		try { ois.close(); } catch (Exception ex) {}
		try { oos.close(); } catch (Exception ex) {}
		try { socket.close(); } catch (Exception ex) {}
	}
	public int getUnitNumber() {
		return unitNumber;
	}
	public void setUnitNumber(int unitNumber) {
		this.unitNumber = unitNumber;
	}
	public String getUnitName() {
		return unitName;
	}
	public void setUnitName(String unitName) {
		this.unitName = unitName;
	}

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}

}








